package com.ruisi.weatherreport.protocol;

import java.lang.ref.WeakReference;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.ruisi.weatherreport.protocol.WeatherInterfaces.DetailWeatherListener;

/**
 * 查询详细天气信息时的回调handler
 * 
 * @author spring ming
 *
 */
public class DetailWeatherInfoHandler extends JsonHttpResponseHandler {
	
	// 构造listener的弱引用，避免内存问题
	WeakReference<DetailWeatherListener> mListenerRef;

	DetailWeatherInfoHandler(DetailWeatherListener l){
		super();
		mListenerRef = new WeakReference<WeatherInterfaces.DetailWeatherListener>(l);
	}
	
	
	/**
	 * 查询成功回调
	 */
	@Override
	public void onSuccess(JSONObject arg) {
		DetailWeatherListener h = mListenerRef.get();
		if(null == h){
			// 如果listrner已经被释放，则不需要回调了
			return;
		}
		
		
		//这里构造WeatherInfo
		WeatherInfo info = new WeatherInfo();
		try {
			JSONObject obj = arg.getJSONObject("weatherinfo");
			
			info.mCityName      = obj.getString ("city");
			info.mCityName_en   = obj.getString ("city_en");
			info.mDate          = obj.getString ("date_y");
			info.mWeekday       = obj.getString ("week");
			info.mCityId        = obj.getString ("cityid");
			for(int i = 1; i < 7; i++){
				info.mTempArray.add(obj.getString("temp" + i));
				info.mWeatherDesArray.add(obj.getString("weather"+i));
				info.mWindDesArray.add(obj.getString("wind"+i));
				info.mWindLevelArray.add(obj.getString("fl"+i));
			}
			info.mWearIndex            = obj.getString ("index");
			info.mWearSuggestion       = obj.getString ("index_d");
			info.m48WearIndex          = obj.getString ("index48");
			info.m48WearSuggestion     = obj.getString ("index48_d");
			info.mUVIndex              = obj.getString ("index_uv");
			info.m48UVIndex            = obj.getString ("index48_uv");
			info.mWashCarIndex         = obj.getString ("index_xc");
			info.mTravelIndex          = obj.getString ("index_tr");
			info.mMorningExerciseIndex = obj.getString ("index_cl");
		} catch (JSONException e) {
			e.printStackTrace();
			h.onFail(WeatherProtocol.PE_JSON_PARSE_ERR, "json parse exception");
			return;
		}
		
		h.onSuccess(info);
	}
	
	/**
	 * 查询失败回调
	 */
	@Override
	public void onFailure(Throwable arg0, String arg1) {
		DetailWeatherListener h = mListenerRef.get();
		if(null == h){
			// 如果listrner已经被释放，则不需要回调了
			return;
		}
		
		h.onFail(-1, arg1);
	}
	
}
